package com.echo.im.client.handler.platform.support;

import com.echo.im.client.handler.platform.AbstractPlatformCmdHandler;
import com.echo.im.client.helper.OnlineStatusHelper;
import com.echo.im.common.model.platform.IMPlatformCmd;
import com.echo.im.common.model.platform.UserLogoutCmd;
import com.echo.im.mq.event.producer.EventPublisher;
import com.echo.im.mq.event.model.PlatformCommandMessageEvent;
import com.echo.im.mq.event.BaseEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author: echo
 * @time: 2024-08-16
 */

@Slf4j
@Component
@RequiredArgsConstructor
public class UserLogoutCmdHandler extends AbstractPlatformCmdHandler<UserLogoutCmd> {

    private final EventPublisher eventPublisher;
    private final PlatformCommandMessageEvent platformCommandMessageEvent;
    private final OnlineStatusHelper onlineStatusHelper;


    @Override
    public void sendPlatformCmd(UserLogoutCmd userLogoutCmd) {
        log.info("Sending platform command: {}", userLogoutCmd);
        Map<Integer, List<Integer>> serverIdTerminalListMap = onlineStatusHelper.getServerIdTerminalListMap(userLogoutCmd.getUserId(), userLogoutCmd.getTerminalList());
        serverIdTerminalListMap.forEach(
                (serverId, terminalList) -> {
                    IMPlatformCmd<UserLogoutCmd> platformCmd = new IMPlatformCmd<>();
                    UserLogoutCmd newUserLogoutCmd = new UserLogoutCmd(userLogoutCmd.getUserId(), terminalList);
                    platformCmd.setData(newUserLogoutCmd);
                    platformCmd.setType(userLogoutCmd.getType());
                    BaseEvent.EventMessage<IMPlatformCmd<UserLogoutCmd>> eventMessage = platformCommandMessageEvent.buildEventMessage(platformCmd);
                    eventPublisher.publishWithServerId(platformCommandMessageEvent.topic(),serverId.toString(), eventMessage);
                }
        );
    }


}
